package com.mccrea.pattern.prototype.deep;

import java.io.*;

/**
 * @author mccrea
 * @version 1.0
 * @description: 实现深拷贝的类
 * @date 2021/5/7 23:54
 */
public class DeepProtoType implements Serializable, Cloneable {
    private static final long serialVersionUID = 5321779033514762003L;
    private String name;
    private DeepCloneableTarget deepCloneableTarget;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public DeepCloneableTarget getDeepCloneableTarget() {
        return deepCloneableTarget;
    }

    public void setDeepCloneableTarget(DeepCloneableTarget deepCloneableTarget) {
        this.deepCloneableTarget = deepCloneableTarget;
    }


    @Override
    public String toString() {
        return "DeepProtoType{" +
                "name='" + name + '\'' +
                ", deepCloneableTarget=" + deepCloneableTarget +
                '}';
    }

    /**
     * @description: 方式一：通过clone()完成深拷贝
     * @author mccrea
     * @date 2021/5/7 23:56
     * @version 1.0
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object deep;
        // 完成对基本类型数据和String的克隆
        deep = super.clone();
        // 对引用类型属性，进行单独处理
        DeepProtoType deepProtoType = (DeepProtoType) deep;
        deepProtoType.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone();
        return deep;
    }

    /**
     * @description: 方式二 通过对象序列化实现（推荐）
     * @author mccrea
     * @date 2021/5/8 0:06
     * @version 1.0
     */
    public Object deepClone() {
        // 输出流
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        // 输入流
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        
        Object o = null;
        try {
            // 对象写入bos中
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            // 从bos中读出对象
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            o = ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert bos != null;
                bos.close();
                assert oos != null;
                oos.close();
                assert bis != null;
                bis.close();
                assert ois != null;
                ois.close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        return o;
    }

}
